package com.xiaoguang.selecttext

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class SelectPopAdapter(
    private val mContext: Context,
    private val mTextList: List<Int>,
    private val mIconList: List<Int>
) : RecyclerView.Adapter<SelectPopAdapter.ViewHolder>() {
    private var itemWrapContent = false
    fun setItemWrapContent(itemWrapContent: Boolean) {
        this.itemWrapContent = itemWrapContent
    }

    private var listener: onClickItemListener? = null
    fun setOnclickItemListener(l: onClickItemListener?) {
        listener = l
    }

    interface onClickItemListener {
        fun onClick(position: Int)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =
            LayoutInflater.from(mContext).inflate(R.layout.item_select_text_pop, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val text = mTextList[position]
        holder.tv_pop_func.text = mContext.resources.getString(text)

        if (itemWrapContent) {
            val params = holder.tv_pop_func.layoutParams
            params.width = ViewGroup.LayoutParams.WRAP_CONTENT
            holder.tv_pop_func.layoutParams = params
            holder.tv_pop_func.setPadding(dp2px(8f), 0, dp2px(8f), 0)
        }

        val drawableId = mIconList[position]
        if (drawableId == 0){
            holder.iv_pop_icon.visibility = View.GONE
        }else {
            holder.iv_pop_icon.visibility = View.VISIBLE
            holder.iv_pop_icon.setBackgroundResource(drawableId)
        }

        holder.ll_pop_item.setOnClickListener { listener?.onClick(position) }
    }

    override fun getItemCount(): Int {
        return mTextList.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ll_pop_item: LinearLayout
        val iv_pop_icon: ImageView
        val tv_pop_func: TextView

        init {
            ll_pop_item = itemView.findViewById(R.id.ll_pop_item)
            iv_pop_icon = itemView.findViewById(R.id.iv_pop_icon)
            tv_pop_func = itemView.findViewById(R.id.tv_pop_func)
        }
    }
}